package servlet;

import mapper.Context;
import mapper.Mapper;
import mapper.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;

    private Mapper mapper;

    public RequestProcessor(Socket socket,  Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {

        try {
            InputStream inputStream = socket.getInputStream();

            Request request  = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            /**
             * 根据URL去Mapper对象中查找Servlet（当然需要⼀级⼀级锁定）
             *  http://localhost:8080/demo1/lagou
             *  http://localhost:8080/demo2/lagou
             */
            String url = request.getUrl();
            //动态请求链接没有存储，则直接返回
            if(!mapper.getServletUrlList().contains(url)){
                return;
            }

            String contextName = url.split("/")[1];
            String wrapperName = url.split("/")[2];

            //进行contexts遍历匹配contextName，获取Wrappers
            for (Context context : mapper.getHost().getContexts()) {

                if(context.getName().equals(contextName)){
                    //进行wrappers遍历匹配wrapperName，获取HttpServlet
                    for (Wrapper wrapper : context.getWrappers()) {

                        if(wrapper.getName().equals(wrapperName)){

                            HttpServlet httpServlet = wrapper.getHttpServlet();
                            httpServlet.service(request,response);
                        }
                    }
                }
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
